import { defineStore } from 'pinia'
import { ref } from 'vue'
// 导入类型（用于开发提示）
import { Equipment } from '../../types/equipment'
// 导入服务
import { getTaskList } from '../../services/task'

export const useInspectionStore = defineStore(
  'inspection',
  () => {
    /**
     * 设备任务列表
     * @type {Ref<Equipment[]>}
     */
     const equipments = ref<Equipment[]>([])

    /**
     * 初始化任务列表 + 映射状态
     */
    const initEquipments = async () => {
      try {
        const res = await getTaskList()
         
        if (res.code === 20000 && Array.isArray(res.data?.taskList)) {
          // 映射并设置 inspectionStatus
          equipments.value = res.data.taskList.map(task => ({
            ...task,
             // 🔁 初始化 inspectionData（如果不存在）
            inspectionData:  createDefaultInspectionData(),
            // 🔁 核心：根据新规则推导 inspectionStatus
            inspectionStatus: getInspectionStatus(task)
          }))
          console.log('设备任务列表',equipments.value)
        } else {
          uni.showToast({ title: '获取任务失败', icon: 'error' })
        }
      } catch (err) {
        uni.showToast({ title: '网络错误', icon: 'error' })
        console.error('Failed to load tasks:', err)
      }
    }

    /**
     * 清空数据
     */
    const clearEquipments = () => {
      equipments.value = []
    }

    /**
 * 根据设备信息计算当前检测状态
 * @param {Equipment} task
 * @returns {'pending_contact'|'pending_inspection'|'inspecting'|'pending_upload'|'completed'}
 */
const getInspectionStatus = (task:any) => {
  // 1. 【最高优先级】已完成： 且 isDetected === 1  (reportImageId 不为空，取消)
  if ( task.isDetected === 1) {
    return 'completed'
  }

  // 2. 是否已预约检测时间？需要 reportId 和 detectionTime 同时存在
  if (task.reportId && task.detectionTime) {
    // 判断三项检测结果是否都存在（非空）
    const hasAllResults =
      task.appearanceDetection &&
      typeof task.appearanceDetection === 'string' &&
      task.appearanceDetection.trim() !== '' &&
      task.componentFunctionDetection &&
      typeof task.componentFunctionDetection === 'string' &&
      task.componentFunctionDetection.trim() !== '' &&
      task.performanceParameterDetection &&
      typeof task.performanceParameterDetection === 'string' &&
      task.performanceParameterDetection.trim() !== ''

    if (hasAllResults) {
      return 'pending_upload' // 所有检测项完成，等待上传
    }

    // 判断是否至少有一项已填写
    const hasAnyResult =
      (task.appearanceDetection && task.appearanceDetection.trim() !== '') ||
      (task.componentFunctionDetection && task.componentFunctionDetection.trim() !== '') ||
      (task.performanceParameterDetection && task.performanceParameterDetection.trim() !== '')

    if (hasAnyResult) {
      return 'inspecting' // 已开始填写任意一项
    } else {
      return 'pending_inspection' // 已预约，但尚未开始检测
    }
  }

  // 3. 默认状态：只要没预约时间，都认为是“待联系卖家”
  return 'pending_contact'
}

    /**
     * 手动更新某个任务的状态（可用于本地操作后刷新 UI）
     * @param {number} reportId
     */
    const updateInspectionStatusByReportId = (reportId:number) => {
      const task = getTaskByReportId(reportId)
      if (task) {
        task.inspectionStatus = getInspectionStatus(task)
        task.updateTime = new Date().toISOString()
      }
    }

     /**
     * 创建默认检测数据
     */
    const createDefaultInspectionData = (): InspectionData => ({
      items: {
        外观: { result: '', remark: '', media: [] },
        部件功能: { result: '', remark: '', media: [] },
        性能参数: { result: '', remark: '', media: [] }
      },
      updatedAt: new Date().toISOString(),
      extendsReportId: 0 // 初始为空
    })
        /**
     * 保存检测草稿
     */
const saveInspectionData = async(reportId, data) => {
   
  const task = getTaskByReportId(reportId)
 
  if (task) {
    if (!task.inspectionData) {
      task.inspectionData = {
        items: {
          外观: { result: '', remark: '', media: [] },
          部件功能: { result: '', remark: '', media: [] },
          性能参数: { result: '', remark: '', media: [] }
        },
        updatedAt: new Date().toISOString(),
        extendsReportId: 0
      }
    }

    Object.assign(task.inspectionData.items, data.items)
    task.inspectionData.updatedAt = new Date().toISOString()
    task.inspectionData.extendsReportId = reportId // ✅ 关键：记录所属任务
    console.log('[Store] 检测数据', task)
    task.updateTime = new Date().toISOString()
  }
}

    // --- 其他辅助方法 ---
    //查询任务id下的设备信息
    const getTaskByReportId = (reportId:number) => {
      return equipments.value.find(e => e.reportId === reportId)
    }
    // 查询设备id下的设备信息
    const getTaskByEquipmentId = (id:any) => {
      return equipments.value.find(e => e.equipmentId === id)
    }
    // 重新计算状态
    const updateInspectionStatus = (reportId:number, status:any) => {
      const task = getTaskByReportId(reportId)
      if (task) {
        task.inspectionStatus = status
        task.updateTime = new Date().toISOString()
      }
    }
    // 重新预约检测时间
    const rescheduleTask = (reportId:number, time:any) => {
      const task = getTaskByReportId(reportId)
      if (task) {
        task.detectionTime = time
        task.updateTime = new Date().toISOString()
        // 重新计算状态
        updateInspectionStatusByReportId(reportId)
      }
    }
    //生成报告
    const submitInspectionResult = (reportId:number) => {
      const task = getTaskByReportId(reportId)
      if (!task || !task.inspectionData) return

      // 此时 appearanceDetection 等字段应已填充
      // 触发状态重算即可
      updateInspectionStatusByReportId(reportId)

      uni.showLoading({ title: '生成报告...' })
      setTimeout(() => {
        uni.hideLoading()
        task.isDetected = 1
        uni.showToast({ title: '提交成功', icon: 'success' })
      }, 800)
    }
    //生成报告成功
    const uploadReportSuccess = (reportId:number, url:any) => {
      const task = getTaskByReportId(reportId)
      if (task) {
        task.reportUrl = url
        task.reportImageId = task.reportImageId || task.reportId // 补充 reportImageId
        task.isDetected = 1
        // 重新计算状态 → 应为 completed
        updateInspectionStatusByReportId(reportId)
        task.updateTime = new Date().toISOString()
      }
    }

    return {
      equipments,
      initEquipments,
      clearEquipments,
      getTaskByReportId,
      getTaskByEquipmentId,
      updateInspectionStatus,
      rescheduleTask,
      saveInspectionData,
      submitInspectionResult,
      uploadReportSuccess,
      // 暴露给外部调用（如页面刷新状态）
      updateInspectionStatusByReportId
    }
  },
  {
    persist: {
      key: 'equipments',
      storage: {
        getItem(key:any) {
          const value = uni.getStorageSync(key)
          return value ? JSON.parse(value) : null
        },
        setItem(key:any, value:any) {
          uni.setStorageSync(key, JSON.stringify(value))
        }
      }
    }
  }
)